package com.alex.statistics.method.timeSeriesAnalysis;


import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LinearRegressionService {

    /**
     * 进行一元回归并返回回归系数 [斜率, 截距]
     *
     * @param xData x 轴数据
     * @param yData y 轴数据
     * @return [斜率, 截距]
     */
    public double[] getCoefficients(List<Double> xData, List<Double> yData) {
        double meanX = calculateMean(xData);
        double meanY = calculateMean(yData);

        double numerator = 0;
        double denominator = 0;

        for (int i = 0; i < xData.size(); i++) {
            numerator += (xData.get(i) - meanX) * (yData.get(i) - meanY);
            denominator += (xData.get(i) - meanX) * (xData.get(i) - meanX);
        }

        double slope = numerator / denominator;
        double intercept = meanY - slope * meanX;

        return new double[]{slope, intercept};
    }

    private double calculateMean(List<Double> data) {
        double sum = 0;
        for (double value : data) {
            sum += value;
        }
        return sum / data.size();
    }

    /**
     * 使用回归系数计算预测值
     *
     * @param x 输入的 x 值
     * @param coefficients 回归系数 [斜率, 截距]
     * @return 预测的 y 值
     */
    public double predict(double x, double[] coefficients) {
        return coefficients[0] * x + coefficients[1];
    }
}
